package com.kelaite.procurement.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.kelaite.procurement.entity.TCompany;
import com.kelaite.procurement.entity.TDemand;
import com.kelaite.procurement.entity.TPipelineHeader;
import com.kelaite.procurement.repository.PipelineHeaderRepository;
import com.kelaite.procurement.service.PipelineHeaderService;

@Service
@Transactional
public class PipelineHeaderServiceImpl implements PipelineHeaderService{
  
	@Autowired
	private PipelineHeaderRepository pipelineHeaderRepository; 
	
	@PersistenceContext
	private EntityManager em;
	
	@Override
	public TPipelineHeader save(TPipelineHeader persistence) {
		return this.pipelineHeaderRepository.save(persistence);
	}

	@Override
	public TPipelineHeader getObject(Long id) {
		return this.pipelineHeaderRepository.findOne(id);
	}

	@Override
	public List<TPipelineHeader> getAll() {
		return this.pipelineHeaderRepository.findAll();
	}

	@Override
	public void deleteByObject(TPipelineHeader persistence) {
		this.pipelineHeaderRepository.delete(persistence);
	}

	@Override
	public void deleteByPrimaryKey(Long id) {
		this.pipelineHeaderRepository.delete(id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<TPipelineHeader> getByProperty(String property, Object value) {
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TPipelineHeader.class).add(Restrictions.eq(property, value));
		return criteria.list();
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<TDemand> getAllDemandByCompany(TCompany company, TDemand demand) {
		Session session = (org.hibernate.Session) em.getDelegate();
		Criteria criteria = session.createCriteria(TPipelineHeader.class)
				.add(Restrictions.eq("tCompany", company))
				.add(Restrictions.isNotNull("tDemand"))
				.addOrder(Order.desc("id"));
		List<TPipelineHeader> pipelineHeaderList = criteria.list();
		List<TDemand> demandList = new ArrayList<TDemand>();
		if(demand != null){
			demandList.add(demand);
		}
		for(TPipelineHeader header : pipelineHeaderList){
			if(!demandList.contains(header.gettDemand())){
				demandList.add(header.gettDemand());
			}
		}
		return demandList;
	}
	
}
